// -----------------------------------------------------------------------
//  <copyright file="DomainEventBus.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/19 22:19</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Properties;


namespace DaprPlus.MediatR;

/// <summary>
/// 领域事件总线的MediatR实现
/// </summary>
/// <param name="mediator"></param>
/// <param name="logger"></param>
public class DomainEventBus(IMediator mediator, ILogger<DomainEventBus> logger) : IDomainEventBus
{
    /// <summary>
    /// 发布领域事件
    /// </summary>
    /// <param name="event">领域事件</param>
    /// <param name="token"></param>
    /// <returns></returns>
    public Task PublishAsync(DomainEvent @event, CancellationToken token = default)
    {
        var source = @event.EventSource.IsNullOrEmpty() ? string.Empty : $" from {@event.EventSource}";
        logger.LogInformation(ResDaprPlus.Format_MediatR_EventBus_Publishing, @event, source);
        var notification = GetNotification(@event);
        return mediator.Publish(notification, token);
    }

    private static INotification GetNotification(DomainEvent @event)
    {
        var notification = (INotification)Activator.CreateInstance(typeof(DomainEventWrap<>).MakeGenericType(@event.GetType()), @event)!;
        return notification;
    }
}
